package resource

import (
	"project-info/src/handle/common"
	"project-info/src/handle/response"
	"project-info/src/model"

	"project-info/src/lib")

type CredentialReq struct {
	Query string `json:"query"`
	common.PageRequest
}

func AddCredential(c *lib.GinContext) error {
	var credential *model.Credential
	if err := c.Bind(&credential); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var count int64
	db := model.DB().Model(&model.Credential{}).Where("name = ?", credential.Name)
	if err := db.Count(&count).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}
	if count > 0 && credential.Id == 0 {
		return response.JsonFail(c, "凭证已存在")
	}

	if credential.Id != 0 {
		if err := model.DB().Save(credential).Error; err != nil {
			return response.JsonFail(c, "保存失败")
		}
	} else {
		if err := model.DB().Create(credential).Error; err != nil {
			return response.JsonFail(c, "保存失败")
		}
	}
	return response.JsonOk(c, credential, "保存成功")
}

func PageCredential(c *lib.GinContext) error {
	var req *CredentialReq
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var credentials []*model.Credential
	var total int64
	db := model.DB().Model(&model.Credential{})
	if req.Query != "" {
		db = db.Where("name like ?", "%"+req.Query+"%")
	}
	if err := db.Count(&total).Order("id desc").Offset((req.Page - 1) * req.Size).Limit(req.Size).Find(&credentials).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}
	return response.JsonOk(c, map[string]interface{}{"records": credentials, "total": total}, "查询成功")
}

func DeleteCredential(c *lib.GinContext) error {
	var credential *model.Credential
	if err := c.Bind(&credential); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	if err := model.DB().Delete(credential).Error; err != nil {
		return response.JsonFail(c, "删除失败")
	}
	return response.JsonOk(c, nil, "删除成功")
}

func ListCredential(c *lib.GinContext) error {
	var credentials []*model.Credential
	if err := model.DB().Find(&credentials).Error; err != nil {
		return response.JsonFail(c, "查询失败")
	}
	var options []*common.OptionRes
	for _, credential := range credentials {
		options = append(options, &common.OptionRes{
			Value: credential.Name,
			Label: credential.Name,
		})
	}
	return response.JsonOk(c, options, "查询成功")
}
